
#!/bin/bash

# Jenkins jobs 目录
JOBS_DIR="/var/lib/jenkins/jobs"
# 保留的构建数量（只保留最近 2 个）
KEEP_BUILDS=2

echo "开始清理 Jenkins Jobs（保留最近 $KEEP_BUILDS 个 builds）..."

find "$JOBS_DIR" -mindepth 1 -maxdepth 1 -type d | while read -r job_dir; do
    job_name=$(basename "$job_dir")
    echo "清理 Job: $job_name"
    
    # 清理 builds 目录（仅保留最近 KEEP_BUILDS 个）
    if [ -d "$job_dir/builds" ]; then
        builds=($(ls "$job_dir/builds" | sort -n))
        total_builds=${#builds[@]}
        
        if [ "$total_builds" -gt "$KEEP_BUILDS" ]; then
            # 计算要删除的旧 builds 数量
            to_delete=$((total_builds - KEEP_BUILDS))
            echo "  保留 ${builds[*]: -$KEEP_BUILDS}，删除最旧的 $to_delete 个 builds"
            
            # 删除旧 builds
            for ((i=0; i<to_delete; i++)); do
                build_num="${builds[$i]}"
                #echo "    删除 build $build_num"
                rm -rf "$job_dir/builds/$build_num"
            done
        else
            echo "  无需清理（只有 $total_builds 个 builds）"
        fi
    fi
done

echo "清理完成！"
echo "当前目录大小: $(du -sh "$JOBS_DIR" | cut -f1)"
